package com.longtailvideo.plugins.captions {


    import flash.display.MovieClip;
    import flash.events.Event;


    public class Animator {


        /** Target MovieClip **/
        private var _tgt:MovieClip;
        /** Transition speed **/
        private var _spd:Number;
        /** Final Alpha **/
        private var _end:Number;
        /** Y position **/
        private var _yps:Number;


        /** Store target to animate. **/
        public function Animator(tgt:MovieClip) {
            _tgt = tgt;
        }


        /** Fade function for MovieClip. **/
        public function fade(end:Number = 1, spd:Number = 0.25):void {
            _end = end;
            if (_tgt.alpha > _end) {
                _spd = -Math.abs(spd);
            } else {
                _spd = Math.abs(spd);
            }
            _tgt.addEventListener(Event.ENTER_FRAME, fadeHandler);
        }


        /** The fade enterframe function. **/
        private function fadeHandler(evt:Event):void {
            if ((_tgt.alpha >= _end - _spd && _spd > 0) || (_tgt.alpha <= _end + _spd && _spd < 0)) {
                _tgt.removeEventListener(Event.ENTER_FRAME, fadeHandler);
                _tgt.alpha = _end;
                if (_end == 0) {
                    _tgt.visible = false;
                }
            } else {
                _tgt.visible = true;
                _tgt.alpha += _spd;
            }
        }


        /** Smoothly move a Movielip to a certain position. **/
        public function easeY(yps:Number, spd:Number = 2):void {
            _spd = spd;
            if (!yps) {
                _yps = _tgt.y;
            } else {
                _yps = yps;
            }
            _tgt.addEventListener(Event.ENTER_FRAME, easeYHandler);
        }


        /** The ease enterframe function. **/
        private function easeYHandler(evt:Event):void {
            if (Math.abs(_tgt.y - _yps) < 1) {
                _tgt.removeEventListener(Event.ENTER_FRAME, easeYHandler);
                _tgt.y = _yps;
            } else {
                _tgt.y = _yps - (_yps - _tgt.y) / _spd;
            }
        }


    }
}